#!/bin/sh

# Download layerspecs and add them automatically to the repo
# Ask adrian.perez@vizzuality.com for more info

# START HERE

# Step 0: copy/move/add this script to .git/hooks/pre-push (create if this file does not exist) and give proper permissions, run chmod +x .git/hooks/pre-push

# 1st: check we're working on the master branch, if we're not then the script finish (exit 1)
# 2nd: dowload each layerspec file and add date at the beggining
# so, in case it doesn't have anything different than the existing file, we have something to commit
# 3rd: git add and commit
# 4th: inform and download (git pull) new possible changes
# 5th: the script ends with exit 0

protected_branch='master'
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

if [ $protected_branch = $current_branch ]
then
    wget https://wri-01.cartodb.com/api/v2/sql?q=SELECT%20*%20FROM%20layerspec_nuclear_hazard -O layerspec_data/layerspec_NHA.json
    wget https://wri-01.cartodb.com/api/v2/sql?q=SELECT%20*%20FROM%20layerspec                -O layerspec_data/layerspec_PRO.json
    wget https://wri-01.cartodb.com/api/v2/sql?q=SELECT%20*%20FROM%20layerspec_adrian_dev     -O layerspec_data/layerspec_DEV.json

    FILES="layerspec_data/layerspec_NHA.json
    layerspec_data/layerspec_PRO.json
    layerspec_data/layerspec_DEV.json"

    now=$(date +%Y%m%d-%T)
    for f in $FILES
    do
      sed -i -e "1s/^/$now /" $f
    done
    rm layerspec_data/*.json-e
    git add -u
    git commit -m "layerspec backup $now"
    echo layerspecs file added to the repo

    git pull --rebase origin master

    exit 0 # push will execute
else
    echo 'Pushing, no file attached'
    exit 0 # push will execute with no file on it
fi
